'use client';

import { useParams, useSearchParams } from 'next/navigation';
import styleButton from '@/styles/Button.module.css';
import styles from './detail.module.css';
import { startTransition, useActionState, useCallback, useEffect, useState } from 'react';

export default function Detail({ data, params, searchParams }) {
    const paramsClient = useParams();
    const searchParamsClient = useSearchParams();
    const [dataClient, setDataClient] = useState(null);

    const [dataClient2, action2, isPending2] = useActionState(async () => {
        const response = await fetch('/api/blog/' + paramsClient.id + '?from=actionState');
        const data = await response.json();

        return data;
    }, null);

    const [dataClient3, action3, isPending3] = useActionState(async () => {
        const response = await fetch('/api/blog/' + paramsClient.id + '?from=actionState2&time='+Date.now());
        const data = await response.json();

        return data;
    }, null)

    let cache = {}
    searchParamsClient.forEach((v, k) => {
        cache[k] = v;
    });
    let fetchData = useCallback(() => {
        startTransition(action3)
    });

    useEffect(() => {
        startTransition(async () => {
            const response = await fetch('/api/blog/' + paramsClient.id);
            const data = await response.json();

            setDataClient(data);
        });

        startTransition(action2)
    }, []);

    
    return (
        <div style={
            {
                'border': '1px solid red'
            }
        } >
            <h1>详情页面</h1>
            <h2>服务端得到参数后传入:</h2>
            <div>params: {JSON.stringify(params)}</div>
            <div>searchParams: {JSON.stringify(searchParams)}</div>
            <div>data: {JSON.stringify(data)}</div>
            
            <div style={{ border: '1px solid yellow', margin: '4px 0' }}></div>
            <h2>客户端得使用hook得到:</h2>
            <div>style: {JSON.stringify(styles)}</div>
            <div>paramsClient: {JSON.stringify(paramsClient)}</div>
            <div>searchParamsClient: {JSON.stringify(cache)}</div>
            <div>直接获取并设置state, dataClient: {dataClient ? JSON.stringify(dataClient) : '正在加载。。。'}</div>
            <div>useActionState得到的action获取自动设置，dataClient2: {dataClient2 ? JSON.stringify(dataClient2) : '正在加载。。。'}</div>
            <div>isPending2: {JSON.stringify(isPending2)}</div>
            <div>按钮事件获取，dataClient3: {dataClient3 ? JSON.stringify(dataClient3) : '--'}</div>
            <div><button className={styleButton.primary} onClick={fetchData}>获取数据{isPending3?'(正在获取...)':''}</button></div>
        </div>
    )
}